package com.cloudshop.service.sms.mq;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cloudshop.service.common.dto.SendPhoneCodeParamsDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 短信发送.
 *
 * @author 宫新程
 * @since 2019/4/21 20:21
 */
@Slf4j
@Component
@RabbitListener(
    bindings = @QueueBinding(exchange = @Exchange("cloud"), value = @Queue("phoneCode")))
public class PhoneCodeMqConsumer {

  @Value("${aliyun.sms.access_key_id}")
  private String accessKeyId;

  @Value("${aliyun.sms.access_secret}")
  private String accessSecret;

  @Value("${aliyun.sms.sign_name}")
  private String signName;

  @Value("${aliyun.sms.template_code}")
  private String templateCode;

  /** 发送短息. */
  @RabbitHandler
  private void sendPhoneCode(SendPhoneCodeParamsDto paramsDto) {
    DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessSecret);
    IAcsClient client = new DefaultAcsClient(profile);
    CommonRequest request = new CommonRequest();
    request.setMethod(MethodType.POST);
    request.setDomain("dysmsapi.aliyuncs.com");
    request.setVersion("2017-05-25");
    request.setAction("SendSms");
    request.putQueryParameter("PhoneNumbers", paramsDto.getPhoneNumbers());
    request.putQueryParameter("SignName", signName);
    request.putQueryParameter("TemplateCode", templateCode);
    request.putQueryParameter("TemplateParam", JSON.toJSONString(paramsDto.getTemplateParam()));
    try {
      CommonResponse response = client.getCommonResponse(request);
      System.out.println(response.getData());
      log.info(
          "短息发送成功！手机号：{}，验证码：{}",
          paramsDto.getPhoneNumbers(),
          paramsDto.getTemplateParam().get("code"));
    } catch (Exception e) {
      log.error("短息发送失败！手机号：{}", paramsDto.getPhoneNumbers());
      e.printStackTrace();
    }
  }
}
